package com.isdust.zor.core.util;

import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import com.google.gson.Gson;
import com.isdust.zor.CoreConfig;
import com.isdust.zor.core.Habitat;

import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Created by zor on 2016/10/17.
 */

public class DbUtil {
    SQLiteDatabase db;

    public DbUtil() {


        File DBPath = new File(CoreConfig.DBPATH);
        if (!DBPath.exists())
            DBPath.mkdirs();
        db = SQLiteDatabase.openOrCreateDatabase(DBPath + "//habit.db", null);
        try {
            create();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void create() {
        db.execSQL(CoreConfig.TAB_CREATE);  //写数据库
    }

    public void drop() {
        db.execSQL(CoreConfig.DB_DROP);
    }
    //    "CREATE TABLE IF NOT EXISTS habit (_id INTEGER PRIMARY KEY AUTOINCREMENT, " +
//            "title VARCHAR, clock VARCHAR, days SMALLINT, " +
//            "yinsi VARCHAR,xiangxian int," +
//            "qiandaosj VARCHAR,createdate VARCHAR)";

    public void insert(Habitat habitat) {
        Gson gson = new Gson();
        db.execSQL(CoreConfig.TAB_INSERT, new Object[]{habitat.title, habitat.clock, habitat.days, habitat.privacy, habitat.catagory, gson.toJson(habitat.getSign(),String[].class), habitat.createdate, habitat.imageID});
    }

    public List<Habitat> getHabits() {
        List<Habitat> tmp = new ArrayList<>();
        Cursor cursor = db.rawQuery("select * from habit", null);
        Gson gson = new Gson();
        while (cursor.moveToNext()) {
            String[]sign = gson.fromJson(cursor.getString(cursor.getColumnIndex("sign")),String[].class);
//            public Habitat(String imageID, String title, String clock, int days, int privacy, int catagory, String createdate, SerializableList<String> sign) {
            Habitat temp = new Habitat(
                    cursor.getString(cursor.getColumnIndex("imageid")),
                    cursor.getString(cursor.getColumnIndex("title")),
                    cursor.getString(cursor.getColumnIndex("clock")),
                    cursor.getInt(cursor.getColumnIndex("days")),
                    cursor.getInt(cursor.getColumnIndex("privacy")),
                    cursor.getInt(cursor.getColumnIndex("catagory")),
                    cursor.getString(cursor.getColumnIndex("createdate")),
                    sign
                    );
            tmp.add(temp);
        }
        return tmp;
    }

    @Override
    protected void finalize() throws Throwable {
        super.finalize();
        db.close();
    }
}
